//
//  NSArray+Lc.m
//  18Birdies
//
//  Created by Lc on 15/6/29.
//  Copyright (c) 2015年 Lc. All rights reserved.
//

#import "LcPreconditions.h"
#import "NSArray+Lc.h"

@implementation NSArray (Lc)

- (BOOL)containsAllObjects:(NSArray*)array {
  for (id object in array) {
    if (![self containsObject:object]) {
      return NO;
    }
  }
  return YES;
}

- (NSSet*)toSet {
  if (self.count == 0) {
    return nil;
  }
  NSMutableSet* set = [NSMutableSet setWithCapacity:self.count];
  for (id object in self) {
    [set addObject:object];
  }
  return set;
}

#pragma mark - Utils

- (NSNumber*)minValue {
  if (self.count == 0) {
    return nil;
  }
  NSArray* sortedArray = [self sortedArrayUsingSelector:@selector(compare:)];
  return sortedArray[0];
}

- (NSNumber*)maxValue {
  if (self.count == 0) {
    return nil;
  }
  NSArray* sortedArray = [self sortedArrayUsingSelector:@selector(compare:)];
  return sortedArray.lastObject;
}

- (int)indexOfMinNumber {
  return [self indexOfMinNumberWithUnique:NO];
}

- (int)indexOfMinNumberWithUnique:(BOOL)unique {
  if (self.count == 0) {
    return -1;
  } else if (self.count == 1) {
    return 0;
  } else {
    NSArray* sortedArray = [self sortedArrayUsingSelector:@selector(compare:)];
    if (unique && [sortedArray[0] floatValue] == [sortedArray[1] floatValue]) {
      return -1;
    }
    NSUInteger index = [self indexOfObject:sortedArray[0]];
    return index != NSNotFound ? (int)index : -1;
  }
}

- (int)indexOfMaxNumber {
  return [self indexOfMaxNumberWithUnique:NO];
}

- (int)indexOfMaxNumberWithUnique:(BOOL)unique {
  if (self.count == 0) {
    return -1;
  } else if (self.count == 1) {
    return 0;
  } else {
    NSArray* sortedArray = [self sortedArrayUsingSelector:@selector(compare:)];
    if (unique &&
        [sortedArray[self.count - 1] floatValue] == [sortedArray[self.count - 2] floatValue]) {
      return -1;
    }
    NSUInteger index = [self indexOfObject:sortedArray[self.count - 1]];
    return index != NSNotFound ? (int)index : -1;
  }
}

@end
